class UsersController < ApplicationController
  before_filter :require_user, :except => [:new, :create]
  
  
  def index
    @users = User.all
    @lands = Land.all
    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end
  
  
  def new
    @user = User.new
    @lands = Land.all
    
    
    respond_to do |format|
      format.html
      format.xml  { render :xml => @user }
    end
  end
  
  def edit
    if is_admin? or params[:id] == current_user.id.to_s then
      @user = User.find(params[:id])
      @lands = Land.all
    else
      redirect_to users_url
      flash[:notice] = "User can't be edited because of your security level"
    end
  end
  
  def destroy
    if is_admin? or params[:id] == current_user.id.to_s then
      @user = User.find(params[:id])
      @user.destroy
      flash[:notice] = "User correctly destroyed"
      
      respond_to do |format|
        format.html { redirect_to(users_url) }
        format.xml  { head :ok }
      end
    else
        redirect_to users_url
      flash[:notice] = "User can't be destroyed because of your security level"
    end
  end
  
  def create
    puts "params :" + params[:user].to_s
    @user = User.new(params[:user])
    
    respond_to do |format|
      if @user.save
        flash[:notice] = "User correctly created"
        format.html { redirect_to(users_url) }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  def update
    @user = User.find(params[:id])
    
    respond_to do |format|
      if @user.update_attributes(params[:user])
        flash[:notice] = "User correctly updated"
        format.html { redirect_to(users_url) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
end
